using System;

using log4net;
using MySql.Data.MySqlClient;

namespace Grr.Models
{
	public class Feature
	{
		private static readonly ILog log = LogManager.GetLogger(typeof(Feature));

		private string text;
		private string title_type;
		private string title_text;

		public Feature()
		{
		}

		public Feature(string title_type, string title_text, string text)
		{
			this.text = text;
			this.title_type = title_type;
			this.title_text = title_text;
		}

		public string Text
		{
			get { return text; }
		}

		public string TitleType
		{
			get { return title_type; }
		}

		public string TitleText
		{
			get { return title_text; }
		}

		public static Feature Empty {
			get { return new Feature(); }
		}


		public static string UrlForFeature(string name)
		{
			return String.Concat("~/feature/", StringUtil.ToFriendlyUri(name));
		}

		public static Feature GetCurrentFeature()
		{
			using (MySqlConnection rcon = DbContext.OpenReadConnection())
			{
				MySqlCommand qcmd = new MySqlCommand("SELECT title_desc, title_text, text FROM Features ORDER BY created_by LIMIT 0,1", rcon);
				MySqlDataReader reader = qcmd.ExecuteReader();

				if (!reader.Read())
				{
					log.Error("No feature foudn for GetCurrentFeature (), returning empty Feature.");
					return Feature.Empty;
				}

				return new Feature(reader.GetString ("title_desc"), reader.GetString ("title_text"), reader.GetString ("text"));
			}
		}

		public static void SetCurrentFeature(string title_desc, string title_text, string text)
		{

		}

		public static Feature QueryForByName(string name)
		{
			using (MySqlConnection rcon = DbContext.OpenReadConnection())
			{
				MySqlCommand qcmd = new MySqlCommand("SELECT title_desc, title_text, text FROM Features WHERE title_text = ?name", rcon);
				qcmd.Parameters.Add(new MySqlParameter("?name", MySqlDbType.VarChar, Validator.MaxFeatureNameLength)).Value = name; 
				MySqlDataReader reader = qcmd.ExecuteReader();

				if (!reader.Read())
				{
					log.Error("No feature found for GetCurrentFeature (), returning empty Feature.");
					return Feature.Empty;
				}

				return new Feature(reader.GetString("title_desc"), reader.GetString("title_text"), reader.GetString("text"));
			}
		}
	}
}

